import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'dva';
import styles from './index.less';
import { Select, Table } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { buildingUtils } from '@/utils/arcgis';
import { getBuildingAttributes } from '@/services/bimServices';
import { SketchPicker } from 'react-color';
import renderColorls from './renderColors';
import cls from 'classnames';
import { useClickAway } from 'react-use';
import { layerUtils, viewUtils, jsapi } from '@/utils/arcgis';

const { Option } = Select;

const columns = [
  {
    title: '属性名称',
    align: 'center',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '颜色',
    align: 'center',
    dataIndex: 'color',
    width: 30,
    key: 'color',
    render: color => (
      <div
        style={{
          background: `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`,
          width: '10px',
          height: '10px',
          marginLeft: '10px',
        }}
      ></div>
    ),
  },
  {
    title: '透明度',
    align: 'center',
    dataIndex: 'opacity',
    width: 50,
    key: 'opacity',
    editable: true,
  },
];

const BimRender = ({ currentBimVersion, onClose }) => {
  const attributes = useRef([]);
  const fieldName = useRef('');
  const [fieldNames, setFieldNames] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  const [colorValue, setColor] = useState({
    r: '191',
    g: '40',
    b: '40',
    a: '0.7',
  });

  const [curKey, setCurKey] = useState('');
  const uniqValueRender = useRef([]);
  
  const tableRef = useRef(null);
  const [displayColorPicker, setDisplayColorPicker] = useState(false);
  useClickAway(tableRef, () => setDisplayColorPicker(false));

  useEffect(() => {
    if (currentBimVersion && !!currentBimVersion.name) {
      getBuildingAttributes(currentBimVersion.url).then(resp => {
        if (resp) {
          if (resp.data) {
            attributes.current = resp.data['summary'];
            const fieldNames = attributes.current.map(e => e.fieldName);
            // fieldNames.splice(fieldNames.indexOf('ObjectId'), 1);
            setFieldNames(fieldNames);
            makeComputedDatasource('Category');
          } else {
            attributes.current = [];
            setFieldNames([]);
          }
        }
      });
    }

    // eslint-disable-next-line
  }, [currentBimVersion.name]);

  function toggleColorPick() {
    setDisplayColorPicker(e => !e);
  }

  const makeComputedDatasource = _fieldName => {
    let attrs = [];
    uniqValueRender.current = [];
    attributes.current &&
      attributes.current.forEach(item => {
        if (item['fieldName'] === _fieldName) {
          fieldName.current = item['fieldName'];
          let color = renderColorls[0];

          item['mostFrequentValues'] &&
            item['mostFrequentValues'].forEach((_key, index) => {
              if (index < 11) {
                color = renderColorls[index];
              } else {
                color = renderColorls[11];
              }
              const data = {
                key: _key,
                name: _key,
                color,
                opacity: '0.7',
              };
              // console.log(data, fieldName);
              attrs.push(data);
              // 生成唯一值renderer
              uniqValueRender.current.push({
                value: `${_key}`,
                symbol: {
                  type: 'mesh-3d',
                  symbolLayers: [
                    {
                      type: 'fill',
                      material: {
                        color,
                        colorMixMode: 'replace',
                      },
                    },
                  ],
                },
              });
            });
        }
      });
    setDataSource(attrs);
  };

  // const hanldeRenderer = () => {
  //   buildingUtils.renderer(
  //     window.agsGlobal.view,
  //     currentBimVersion.name,
  //     dataSource,
  //     // fieldName.current,
  //   );
  // };

  // 开始唯一值渲染
  async function hanldeRendererClick() {
    console.time('color-render-start');
    console.log('--------');
    const view = await viewUtils.isViewReady();
    const buildingLayer = layerUtils.getLayerByTitle(view, currentBimVersion.name);
    buildingLayer.allSublayers.forEach(subLayer => {
      subLayer.renderer = {
        type: 'unique-value',
        // valueExpression: !flag ? '' : valueExpression,
        field: fieldName.current,
        uniqueValueInfos: uniqValueRender.current,
      };
    });
    view.goTo(buildingLayer.fullExtent);
    console.timeEnd('color-render-start');
    console.log('--------');
  }

  // 修改table中的颜色
  const handleChangeColor = color => {
    setColor(color.rgb);
    setDataSource(_dataSource =>
      _dataSource.map(e => {
        if (e.key == curKey) {
          e.color = color.rgb;
          e.opacity = color.rgb.a;
        }
        return e;
      }),
    );

    uniqValueRender.current.forEach(e => {
      if (e.value == curKey) {
        e.symbol.symbolLayers[0].material.color = color.rgb;
      }
    });
  };

  // 处理行点击
  const handleClickRow = record => {
    toggleColorPick();
    setCurKey(record.key);
  };

  //
  const handleCancel = async () => {
    const view = await viewUtils.isViewReady();
    buildingUtils.refresh(view, currentBimVersion.name);
  };


  return (
    <div className={cls(styles.panel, 'base-panel')}>
      <div className={'base-panel-title'}>
        以属性值渲染模型
        <span className={'base-panel-title-btn'}>
          <CloseOutlined onClick={onClose} />
        </span>
      </div>
      <div className="base-panel-body" style={{ height: 'auto', overflow: 'inherit' }}>
        <div className={styles.container}>
          <span>请选择该模型使用的属性字段</span>

          <Select defaultValue="Category" onChange={makeComputedDatasource}>
            {fieldNames.map(item => (
              <Option value={item}>{item}</Option>
            ))}
          </Select>

          <div className={styles['table']} ref={tableRef}>
            {displayColorPicker && (
              <div style={{ position: 'absolute', left: -100, zIndex: 66 }}>
                <SketchPicker color={colorValue} onChange={handleChangeColor} />
              </div>
            )}
            <Table
              dataSource={dataSource}
              columns={columns}
              pagination={{ pageSize: 5, showSizeChanger: false }}
              bordered={true}
              onRow={record => {
                return {
                  onClick: event => {
                    handleClickRow(record);
                  }, // 点击行
                };
              }}
            />
          </div>
        </div>

        <div className={styles['buttons']}>
          <span onClick={hanldeRendererClick} className={styles['button']}>
            自动渲染
          </span>
          <span onClick={handleCancel}>还原</span>
        </div>
      </div>
    </div>
  );
};

export default connect(({ bimmodel }) => {
  return {
    currentBimVersion: bimmodel.currentBimVersion,
  };
})(BimRender);
